<!-- 角色管理 -->
<template>
  <div class="main">
    <!-- 添加角色 -->
    <div class="role">
      <el-space wrap>
        <span>角色名称：</span>
        <el-input v-model.trim='role.name' />
        <span>描述信息：</span>
        <el-input v-model.trim='role.desc' />
        <el-button type="primary" @click="addto"  v-permission='"sys:role:create"' >添加</el-button>
      </el-space>
    </div>

    <!-- 角色管理列表 -->
    <div class="role-list">
      <el-table :data="settableData.list" style="width: 100%" border>
        <el-table-column prop="name" label="角色名称" align="center" />
        <el-table-column prop="desc" label="说明" align="center" />
        <el-table-column prop="address" label="操作" align="center">
          <template #default="scope">
            <div v-if="scope.row.id!=1">
              <el-button type="primary" size="small" @click="setmodify(scope.row)" v-permission='"sys:role:update"'>修改</el-button>
              <el-button type="primary" size="small" @click="PermissionList(scope.row)">权限</el-button>
              <el-button type="danger" size="small" @click="getdelect(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <PagingList @Change="giterList" :listdata="listdata"></PagingList>

    <!-- 角色修改配置权限对话框 -->
    <el-dialog v-model="dialogTableVisible" :title="judge?'修改信息':'权限信息'" :width="judge?'50%':'30%'"
      :before-close="handleClose">
      <div v-if="judge">
        <el-space wrap>
          <span>角色名称：</span>
          <el-input v-model.trim='form.name' />
          <span>描述信息：</span>
          <el-input v-model.trim='form.desc' />
          <el-button type="primary" @click="modify">修改</el-button>
        </el-space>
      </div>
      <div v-else>
        <el-tree :data="dataper" show-checkbox node-key="id" :default-checked-keys="defaultChecked.roleAnd"
          :props="defaultProps" ref="tree">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <div v-if="!data.children">{{data.id}}</div>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <div v-if="!judge">
          <span class="dialog-footer">
            <el-button @click="dialogTableVisible = false">取消</el-button>
            <el-button type="primary" @click="Snakeskin">确定</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { post } from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive } from "vue";
import { Pagination } from "#/index";

const judge = ref(false) //判断是修改还是配置
const settableData = reactive({//列表数据
  list: [] as string[]
})
let role = reactive({ //添加数据
  name: '',//名称
  desc: ''//描述
})
let listdata = reactive(new Pagination()) //分页数据
// 分页
const giterList = (e: any) => { //获取下一页的数据并赋值
  listdata = e
  getrolelist()
}
let form = reactive({ //修改数据
  id: '',
  name: '',
  desc: ''
})
// 配置权限数据
let id = ref('') //当前默认配置的id
let dataper = ref([]) //权限列表数据
let defaultChecked = reactive({
  roleAnd: [] as string[]
})//默认选中的数据
let defaultProps = ref({  //列表渲染的数据
  children: 'children',//第二层的数据
  label: 'label'//最外面的数据

})
let tree = ref()
const dialogTableVisible = ref(false)//控制权限对话框显示和隐藏


// 获取角色列表数据
const getrolelist = () => {
  let data = {
    _gp: 'admin.role',
    _mt: 'list',
    page: listdata.page,
    limit: listdata.limit
  }
  post(data).then(res => {
    console.log(res);
    let { data } = res
    settableData.list.length = 0
    settableData.list.push(...data.items)
    listdata.total = data.total
  })
}
getrolelist()

// 角色添加
const addto = () => {
  if (role.name == "") { //判断用户名不能为空
    ElMessage.error("角色名称不能为空!")
    return
  }
  let data = {
    _gp: 'admin.role',
    _mt: 'create',
    role: JSON.stringify(role)
  }
  post(data).then((res) => {
    console.log(res);
    let { data, errmsg, errno } = res
    if (200 == errno) {
      ElMessage.success("添加成功!")
      getrolelist()
      role.name = ""
      role.desc = ""
    } else {
      ElMessage.warning('角色已存在')
    }
  })
}

// 点击弹出框赋值
const setmodify = (row:any) => {
  judge.value = true
  dialogTableVisible.value = true
  form.id = row.id
  Object.assign(form, row) //浅拷贝  第一个参数是目标,第二个参数是源对象
}
//角色修改
const modify = () => {
  if (form.name == "") {
    ElMessage.error("角色名称不能为空!")
    return
  }
  let data = {
    _gp: 'admin.role',
    _mt: 'update',
    role: JSON.stringify(form)
  }
  post(data).then(res => {
    console.log(res);
    let { errno } = res
    if (200 == errno) {
        ElMessage.success("修改成功!")
        getrolelist()
        dialogTableVisible.value = false
    } else {
      ElMessage.warning("角色已存在")
    }

  })
}

// 打开配置权限框权限列表
const PermissionList = (row: any) => {
  id.value = row.id
  judge.value = false
  let data = {
    _gp: 'admin.role',
    _mt: 'permissionList',
    roleId: id.value
  }
  post(data).then(res => {
    console.log(res);
    let { data } = res
    dataper.value = data.systemPermissions
    defaultChecked.roleAnd.length = 0
    defaultChecked.roleAnd.push(...data.assignedPermissions)
    dialogTableVisible.value = true
  })
}
// 配置权限
const Snakeskin = () => {
  let rule_ids = tree.value.getCheckedKeys() //获取选中的key值
  let data = {
    _gp: "admin.role",
    _mt: 'permissionSet',
    roleSetPermissionDTO: JSON.stringify({ roleId: id.value, permissions: rule_ids })
  }
  post(data).then(res => {
    console.log(res);
    let { data, errno, errmsg } = res 
    if (200 == errno) {
      dialogTableVisible.value = false
      getrolelist()
      ElMessage.success('配置成功！')
    } else {
      ElMessage.warning(errmsg)
    }
  })
}



// 角色删除
const getdelect = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '删除角色',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let data = {
        _gp: 'admin.role',
        _mt: 'delete',
        roleId: row.id,
      }
      post(data).then(res => {
        console.log(res);
        let { errno, errmsg } = res 
        if (200 == errno) {
          getrolelist()
          ElMessage({
            type: 'success',
            message: '删除成功！',
          })
        }else{
          ElMessage.warning(errmsg)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功！',
      })
    })
}

// 点击关闭时弹出
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('您确定要关闭此对话框吗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
</script>

<style lang="less" scoped>
.main {
  .role-list {
    margin: 25px 0px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>
